require 'skit/logger'
require 'daemon_kit'
require 'erb' # for daemon_kit/config
require 'amqp'

module Skit
  module AMQP
    class Runner
      def initialize
        @config = DaemonKit::Config.load('amqp').to_h( true )
      end

      def run(&block)
        starting

        # Start our event loop and AMQP client
        ::AMQP.start(@config) do |connection|
          hook = proc { connection.close { EventMachine.stop }}
          DaemonKit.trap('INT', hook)
          DaemonKit.trap('TERM', hook)

          handle_tcp_connection_loss(connection)

          yield connection
        end
      end

      def starting
        config_without_pass = @config.merge(pass: '***')
        Skit.logger.debug("AMQP.start(#{config_without_pass.inspect})")
      end

      def handle_tcp_connection_loss(connection)
        connection.on_tcp_connection_loss do |client, settings|
          notify_tcp_connection_loss(client, settings)
          client.reconnect(false, 10)
        end

        connection.on_recovery do |client, settings|
          notify_tcp_connection_recovery(client, settings)
        end
      end

      def notify_tcp_connection_loss(client, settings)
        status = client.status
        host = settings[:host]
        Skit.logger.error("RabbitMQ connection #{status}: #{host}. Reconnecting.")
        Skit.stats.increment('service.connecting') if Skit.respond_to?(:stats) # TODO: refactor
      end

      def notify_tcp_connection_recovery(client, settings)
        host = settings[:host]
        Skit.logger.info("Connection recovered, now connected to #{host}")
      end
    end
  end
end
